from flask import Flask,request,jsonify
from SenseVoice import *
import uuid
import os
import requests
import dashscope
from flask_cors import CORS

app = Flask(__name__)
CORS(app)



@app.route("/tts",methods=["GET"])
def tts():

    text = request.args.get("text", "")
    response = dashscope.audio.qwen_tts.SpeechSynthesizer.call(
        model="qwen-tts",
        api_key="keyxxxxxxxxxxxxxxxxxxxxxx",
        text=text,
        voice="Cherry",
    )
    
    save_dir = "/dir/"
    audio_url = response.output.audio["url"]
    random_Word = str(uuid.uuid4())[:8]+".wav"
    save_path = save_dir + random_Word  # 自定义保存路径

    try:
        response = requests.get(audio_url)
        response.raise_for_status()  # 检查请求是否成功
        with open(save_path, 'wb') as f:
            f.write(response.content)
        print(f"音频文件已保存至：{save_path}")
    except Exception as e:
        print(f"下载失败：{str(e)}")
    
    return save_path,200



@app.route("/voiceapi",methods=["POST"])
def SenseVoiceApi():

    if "vfile" not in request.files:
        return jsonify({"error": "No voice file part"}),400
    #获取传过来的mp3文件或者是wav音频文件

    input_voice = request.files["vfile"]

    if input_voice.filename == "":
        return jsonify({"error": "No selected file"}), 400
    
    if not (input_voice.filename.lower().endswith('.mp3') or input_voice.filename.lower().endswith('.wav')):
        return jsonify({"error": "Only MP3 and WAV files are allowed"}), 400
    
    detecte_voice = None

    output_dir = "./output_voice/"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    voice_path = output_dir+input_voice.filename
    input_voice.save(voice_path)
    sv = SenseVoice()
    #params:input_wav 传入的音频文件   language 选择的语言 fs 时长 dafult = 16000
    language = "zh"

    detecte_voice = sv.model_inference(voice_path,language)
     
    return detecte_voice,200


if __name__ == "__main__":
    app.run(debug=True,
            port=5005)




